use anyhow::{bail, Result};
use std::env;
use std::fs::File;

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AppConfig {
    pub server: ServerConfig,
}

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ServerConfig {
    pub port: u32,
    pub db_url: String,
}

impl AppConfig {
    #[allow(dead_code)]
    pub fn load() -> Result<Self> {
        let ret = match (
            File::open("send.yml"),
            File::open("../send.yml"),
            env::var("SEND_CONFIG"),
        ) {
            (Ok(reader), _, _) => serde_yaml::from_reader(reader),
            (_, Ok(reader), _) => serde_yaml::from_reader(reader),
            (_, _, Ok(path)) => serde_yaml::from_reader(File::open(path)?),
            _ => bail!("no config file"),
        };
        Ok(ret?)
    }
}
